import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { Router } from 'vue-router'
import {
  MessageAlertProps,
  MessageTypeEnum,
} from '@/components/MessageAlert/type.ts'
import { debounce } from '@/utils/func'

// 从外部导入一下router
let router: Router = null
export const setComponentStoreRouter = (r: Router) => {
  router = r
}

//
//
// MessageAlert 组件全局状态
export const useMessageAlertStore = defineStore('messageAlert', () => {
  // 是否可见
  const alertVisible = ref<boolean>(false)
  // 参数
  const alertParam = ref<MessageAlertProps>({})

  const initAlert = (
    param: MessageAlertProps | string,
    type: MessageTypeEnum | string
  ) => {
    alertParam.value.duration = true
    useRequestLoadingStore().closeRequestLoading()

    if (typeof param === 'string')
      alertParam.value = { ...alertParam.value, content: param }

    if (typeof param === 'object')
      alertParam.value = { ...alertParam.value, ...param }

    alertParam.value.type = type
    alertVisible.value = true
  }

  // 打开弹窗
  const openAlert = {
    success: (param: MessageAlertProps | string) => initAlert(param, 'success'),
    info: (param: MessageAlertProps | string) => initAlert(param, 'info'),
    error: (param: MessageAlertProps | string) => initAlert(param, 'error'),
    warning: (param: MessageAlertProps | string) => initAlert(param, 'warning'),
  }

  // 关闭弹窗
  function closeAlert() {
    alertVisible.value = false
    setTimeout(() => (alertParam.value = {}), 100)
  }

  return {
    alertVisible: computed(() => alertVisible.value),
    alertParam: computed(() => alertParam.value),
    openAlert: computed(() => openAlert),
    closeAlert,
  }
})

//
//
// RequestLoading 组件全局状态
export const useRequestLoadingStore = defineStore('requestLoading', () => {
  // 是否可见
  const requestLoadingVisible = ref<boolean>(false)
  // 请求队列
  const requestQueue = ref<string[]>([])

  // 判断哪些页面不需要请求loading
  const judgePage = (path: string): boolean => {
    const noShowPageList = ['/', '/login']
    return noShowPageList.includes(path)
  }

  // 判断哪些请求需要loading
  const judgeRequest = (url: string): boolean => {
    function isStartsWith(str1: string, str2: string) {
      // 确保较短的字符串作为前缀
      const shorter = str1.length <= str2.length ? str1 : str2
      const longer = str1.length > str2.length ? str1 : str2
      return longer.startsWith(shorter)
    }

    // 需要使用到loading的请求路径
    const showRequestList = [
      '/api/login',
      '/user/info',
      '/user/getAccessRoutes',
    ]
    return showRequestList.some((item) => isStartsWith(item, url))
  }

  // 添加队列
  function addQueue(str: string, requestUrl: string = '') {
    const path = router.currentRoute.value.path

    if (judgePage(path)) {
      if (requestUrl !== '' && judgeRequest(requestUrl)) {
        requestQueue.value = [str, ...requestQueue.value]
        requestLoadingVisible.value = true
      } else requestLoadingVisible.value = false
    } else {
      requestQueue.value = [str, ...requestQueue.value]
      requestLoadingVisible.value = true
    }
  }

  const visibleDebounce = debounce(() => {
    requestLoadingVisible.value = false
  }, 1000)

  // 删除队列
  function shiftQueue() {
    requestQueue.value.shift()
    if (requestQueue.value.length === 0) visibleDebounce()
  }

  // 关闭loading
  function closeRequestLoading() {
    requestQueue.value = []
    requestLoadingVisible.value = false
  }

  return {
    requestLoadingVisible: computed(() => requestLoadingVisible.value),
    addQueue,
    shiftQueue,
    closeRequestLoading,
  }
})
